﻿/* Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
 
Copyright (C) 2010 by Tomasz Pluskiewicz

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Threading;
using Yama.Util.CodeContracts;

namespace Yama.Util
{
    ///<summary>
    /// Converts an Enum into localized strings using translations from a resx file.
    ///</summary>
    public class EnumLocalizer : EnumConverter
    {
        protected readonly ResourceManager ResourceManager;

        /// <summary>
        /// Creates new instance of EnumLocalizer
        /// </summary>
        /// <param name="type">enum type to localize</param>
        public EnumLocalizer(Type type)
            : base(type)
        {
            var attributes = type.GetCustomAttributes(typeof(ResourcePathAttribute), false);

            if (attributes.Length == 0)
                throw new Exception("Enum is missing ResourcePathAttribute");

            try
            {
                ResourcePathAttribute attribute = (ResourcePathAttribute) attributes[0];

                string resourcePath = attribute.Path;

                Assembly assembly = string.IsNullOrEmpty(attribute.AssemblyName)
                                        ? Assembly.GetAssembly(type)
                                        : Assembly.Load(attribute.AssemblyName);

                ResourceManager = new ResourceManager(resourcePath, assembly);
            }
            catch(Exception ex)
            {
                throw new Exception("Cannot create ResourceManager", ex);
            }
        }

        public override object ConvertTo(ITypeDescriptorContext context,
                                         CultureInfo culture, object value, Type destinationType)
        {
            string resourceKey = Enum.GetName(value.GetType(), value);

            try
            {
                return ResourceManager.GetString(resourceKey);
            }
            catch
            {
                return Enum.GetName(value.GetType(), value);
            }
        }

        /// <summary>
        /// Gets all values of an Enum and translates the names based on resource given
        /// via ResourcePathAttribute
        /// </summary>
        /// <returns>Localized set of enum's values</returns>
        public IEnumerable GetValues()
        {
            return Enum.GetValues(EnumType);
        }

        /// <summary>
        /// Gets enum value represented by the string
        /// </summary>
        /// <param name="text">enum text</param>
        /// <returns>enum value</returns>
        public object Parse(string text)
        {
            string resourceKey = null;

            var resourceSet = ResourceManager.GetResourceSet(
                Thread.CurrentThread.CurrentUICulture,
                true,
                true);

            foreach (DictionaryEntry resource in resourceSet)
            {
                if ((string) resource.Value != text) continue;

                resourceKey = (string)resource.Key;
                break;
            }

            Check.Assert(resourceKey != null, string.Format("Resource key for value {0} not found", text));

            return Enum.Parse(EnumType, resourceKey);
        }

        /// <summary>
        /// Gets string representing the enum value
        /// </summary>
        public string GetName(object value)
        {
            return (string)ConvertTo(value, typeof(string));
        }

        /// <summary>
        /// Returns localized strings for all values of the enum type
        /// </summary>
        public IEnumerable<string> GetNames()
        {
            foreach (var value in GetValues())
            {
                yield return GetName(value);
            }
        }

        /// <summary>
        /// Returns pairs of values/names for the current language
        /// </summary>
        public IEnumerable<KeyValuePair<object, string>> GetValueNamePairs()
        {
            return from object value in GetValues() 
                   select new KeyValuePair<object, string>(value, GetName(value));
        }
    }

    public class EnumLocalizer<TEnum> : EnumLocalizer
    {
        public EnumLocalizer()
            : base(typeof(TEnum))
        {
        }

        /// <summary>
        /// Gets enum value represented by the string
        /// </summary>
        /// <param name="text">enum text</param>
        /// <returns>enum value</returns>
        public new TEnum Parse(string text)
        {
            string resourceKey = null;

            var resourceSet = ResourceManager.GetResourceSet(
                Thread.CurrentThread.CurrentUICulture,
                true,
                true);

            foreach (DictionaryEntry resource in resourceSet)
            {
                if ((string) resource.Value != text) continue;

                resourceKey = (string)resource.Key;
                break;
            }

            Check.Assert(resourceKey != null, string.Format("Resource key for value {0} not found", text));

            return (TEnum)Enum.Parse(EnumType, resourceKey);
        }
    }
}